//
//  SelectCityViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/9.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "SelectProvinceCityViewController.h"
#import "GetAllProvincesResponse.h"

@interface SelectProvinceCityViewController ()

@property (nonatomic,strong) UITableView *nationTable;
@property (nonatomic,strong) UITableView *provinceTable;
@property (nonatomic,strong) UITableView *cityTable;

@property (nonatomic,strong) NSMutableArray *nationDataSource;
@property (nonatomic,strong) NSMutableArray *provinceDataSource;
@property (nonatomic,strong) NSMutableArray *cityDataSource;
@property (nonatomic,strong) NSIndexPath *oldIndexPath;




@end

@implementation SelectProvinceCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.nationDataSource = [NSMutableArray new];
    self.provinceDataSource = [NSMutableArray new];
    self.cityDataSource = [NSMutableArray new];
    //self.selectedCities = [NSMutableArray new];
    self.oldIndexPath = nil;
}

#pragma mark - 初始化视图
- (void)setupViews{
    //自定义完成选择按钮
//    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成选择" style:UIBarButtonItemStyleDone target:self action:@selector(onSave)];
//    self.navigationItem.rightBarButtonItem = saveBtn;
    
    //自定义返回按钮
    UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
    self.navigationItem.leftBarButtonItem = returnBtn;
    
    self.nationTable = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.nationTable.width = kScreen_Width/3;
    self.nationTable.layer.borderWidth = 0.5;
    self.nationTable.layer.borderColor = [[UIColor grayColor] CGColor];
    self.nationTable.hidden = YES;
    
    self.nationTable.delegate = self;
    self.nationTable.dataSource = self;
    [self.view addSubview:self.nationTable];
    
    
    self.provinceTable = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.provinceTable.width = kScreen_Width/3;
    self.provinceTable.x = kScreen_Width/3;
    self.provinceTable.layer.borderWidth = 0.5;
    self.provinceTable.layer.borderColor = [[UIColor grayColor] CGColor];
    self.provinceTable.hidden = YES;
    
    self.provinceTable.delegate = self;
    self.provinceTable.dataSource = self;
    [self.view addSubview:self.provinceTable];
    
    self.cityTable = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
//    self.cityTable.layer.borderWidth = 1.0;
//    self.cityTable.layer.borderColor = [[UIColor grayColor] CGColor];
    self.cityTable.width = kScreen_Width/3;
    self.cityTable.x = 2*kScreen_Width/3;
    self.cityTable.layer.borderWidth = 0.5;
    self.cityTable.layer.borderColor = [[UIColor grayColor] CGColor];
    
    self.cityTable.delegate = self;
    self.cityTable.dataSource = self;
    [self.view addSubview:self.cityTable];
    self.cityTable.hidden = YES;
 
    
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    [self loadNationData];
}

-(void)loadNationData{    
    [HttpClient getWithUrl:HTTP_GET_NATIONS paramDic:nil resultClass:[GetAllProvincesResponse class] success:^(GetAllProvincesResponse *response) {
        if (response.getAllNationsResult.count > 0) {
            [self.nationDataSource removeAllObjects];
            for (ProvinceData *item in response.getAllNationsResult) {
                [self.nationDataSource addObject:item];
            }
            self.nationTable.hidden = NO;
            [self.nationTable reloadData];
        }
        else {
            NSLog(@"请求省份失败！");
        }
        
    } failure:^(NSError *error) {
        NSLog(@"请求省份失败！");
    }];
}


-(void)loadProvinceData:(NSString*)nationId {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:nationId forKey:@"nid"];
    
    [HttpClient getWithUrl:HTTP_GET_PROVINCES paramDic:dic resultClass:[GetAllProvincesResponse class] success:^(GetAllProvincesResponse *response) {
        if (response.getAllProvincesResult.count > 0) {
            [self.provinceDataSource removeAllObjects];
            for (ProvinceData *item in response.getAllProvincesResult) {
                [self.provinceDataSource addObject:item];
            }
            self.provinceTable.hidden = NO;
            [self.provinceTable reloadData];
        }
        else {
            NSLog(@"请求省份失败！");
        }
        
    } failure:^(NSError *error) {
        CMLog(@"请求省份失败！，错误信息为%@",error);
    }];
}



-(void)loadCitysData:(NSString*)provinceId {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:provinceId forKey:@"pid"];
    
    [HttpClient getWithUrl:HTTP_GET_CITYS paramDic:dic resultClass:[GetAllProvincesResponse class] success:^(GetAllProvincesResponse *response) {
        if (response.getAllCitiesResult.count > 0) {
            [self.cityDataSource removeAllObjects];
            for (ProvinceData *item in response.getAllCitiesResult) {
                //判断是否有城市已经在选择的数据里
                BOOL hasSelected = NO;
                ProvinceData *hasSelectedItem = nil;
                for (ProvinceData *selected in self.selectedCities) {
                    if ([selected.guidId isEqualToString:item.guidId]) {
                        hasSelected = YES;
                        hasSelectedItem = selected;
                        break;
                    }
                }
                if (hasSelected) {
                    [self.cityDataSource addObject:hasSelectedItem];
                }
                else {
                    [self.cityDataSource addObject:item];
                }
                
            }
            self.cityTable.hidden = NO;
            [self.cityTable reloadData];
        }
        else {
            NSLog(@"请求城市失败！");
        }
        
    } failure:^(NSError *error) {
        NSLog(@"请求城市失败！");
    }];
}

#pragma mark - 事件响应
- (void)onSave {
    if (self.selectedCities.count == 0) {
        kTipAlert(@"您还没有选择城市！");
        return;
    }
    if (self.delegate != nil) {
        [self.delegate finishedSelected:self.selectedCities];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onReturn {
    if (self.selectedCities.count == 0) {
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"您还没有选择城市" delegate:self cancelButtonTitle:@"继续选择" otherButtonTitles:@"不选了", nil] show];
        return;
    }
    if (self.delegate != nil) {
        [self.delegate finishedSelected:self.selectedCities];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIAlertViewDelegate 代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.nationTable) {
        return self.nationDataSource.count;
    }
    else if (tableView == self.provinceTable) {
        return self.provinceDataSource.count;
    }
    else {
        return self.cityDataSource.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.nationTable) {
        static NSString *identifier = @"NationCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        ProvinceData *item = [self.nationDataSource objectAtIndex:indexPath.row];
        cell.textLabel.text = item.name;
        return cell;
    }
    else if (tableView == self.provinceTable) {
        static NSString *identifier = @"ProvinceCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        ProvinceData *item = [self.provinceDataSource objectAtIndex:indexPath.row];
        cell.textLabel.text = item.name;
        return cell;
    }
    else {
        static NSString *identifier = @"CityCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        
        ProvinceData *item = [self.cityDataSource objectAtIndex:indexPath.row];
        if (item.isSelected) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        cell.textLabel.text = item.name;
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.nationTable) {
        ProvinceData *item = [self.nationDataSource objectAtIndex:indexPath.row];
        self.oldIndexPath = nil;
        [self loadProvinceData:item.guidId];
    }
    else if (tableView == self.provinceTable) {
        ProvinceData *item = [self.provinceDataSource objectAtIndex:indexPath.row];
        self.oldIndexPath = nil;
        [self loadCitysData:item.guidId];
    }
    else {
        ProvinceData *item = [self.cityDataSource objectAtIndex:indexPath.row];
        if (self.selectedCities == nil) {
            self.selectedCities = [NSMutableArray new];
        }
        if (self.couldMultipleSelect) {
            //多选
            item.isSelected = !item.isSelected;
            [self.cityTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            if (item.isSelected) {
                [self.selectedCities addObject:item];
            }
            else {
                [self.selectedCities removeObject:item];
            }
            
            //给出提示
            NSMutableString *selectStr = [NSMutableString new];
            if (self.selectedCities.count > 0) {
                [selectStr appendString:@"您已经选择了："];
                for (ProvinceData *selected in self.selectedCities) {
                    [selectStr appendString:selected.name];
                    [selectStr appendString:@" "];
                }
            }
            else {
                [selectStr appendString:@"您当前没有选择城市"];
            }
            [Tools showMessageCenter:selectStr];
        }
        else {
            [self.selectedCities removeAllObjects];
            [self.selectedCities addObject:item];
            if (self.delegate != nil) {
                [self.delegate finishedSelected:self.selectedCities];
            }
            [self.navigationController popViewControllerAnimated:YES];
//            if (self.oldIndexPath == nil) {
//                item.isSelected = !item.isSelected;
//                self.oldIndexPath = indexPath;
//                [self.selectedCities addObject:item];
//                [self.cityTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//            }
//            else if (self.oldIndexPath == indexPath){
//                item.isSelected = !item.isSelected;
//                if (item.isSelected) {
//                    [self.selectedCities addObject:item];
//                }
//                [self.cityTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//            }
//            else {
//                item.isSelected = YES;
//                [self.selectedCities addObject:item];
//                ProvinceData *oldItem = [self.cityDataSource objectAtIndex:self.oldIndexPath.row];
//                oldItem.isSelected = NO;
//                [self.cityTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, self.oldIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//                self.oldIndexPath = indexPath;
//            }
        }
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
